package com.houger.ddd.common.utils;
import com.houger.ddd.common.utils.ResultCode;
import lombok.Data;
import lombok.Getter;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.io.Serializable;

@Data
//统一返回结果的类
public class R<T> implements Serializable {

    private Integer code;


    private String message;

//    @ApiModelProperty(value = "返回数据")
//    private Map<String, Object> data = new HashMap<String, Object>();

    @Getter
    private T data;

    //把构造方法私有
    private R() {
    }

    public static <T> R<T> ok(T data){
        final R<T> r = new R<>();
        r.setCode(StatusCode.SUCCESS.getCode());
        r.setData(data);
        r.setMessage("success");
        return r;
    }

    public static <T> R<T> error(StatusCode statusCode){
        final R<T> r = new R<>();
        r.setCode(statusCode.getCode());
        r.setMessage(statusCode.getMsg());
        return r;
    }
    public static <T> R<T> error(Integer code,String msg){
        final R<T> r = new R<>();
        r.setCode(code);
        r.setMessage(msg);
        return r;
    }
    public static <T> R<T> error(BusinessException e){
        final R<T> r = new R<>();
        r.setCode(StatusCode.ERROR.getCode());
        r.setMessage(ExceptionUtils.getMessage(e));
        return r;
    }



    public R<T> message(String message){
        this.setMessage(message);
        return this;
    }


    public R<T> code(Integer code){
        this.setCode(code);
        return this;
    }

    public void setData(T data) {
        this.data = data;
    }
}
